package router

import (
	"net/http"
	"os"
	"werewolf/handlers"
)

var serverFilePrefix = "/var/www/Werewolf/"

func ServerInit() http.Handler {

	localPath()
	mux := http.NewServeMux()
	handler := corsMiddleware(mux)
	mux.HandleFunc("/create", handlers.CreateHandler)
	mux.HandleFunc("/operation", handlers.OperationHandler)
	mux.HandleFunc("/play", handlers.PlayHandler)
	mux.HandleFunc("/reissue", handlers.ReissueHandler)
	mux.HandleFunc("/room", handlers.RoomHandler)
	mux.HandleFunc("/view", handlers.ViewHandler)
	mux.HandleFunc("/ws", handlers.WebSocketHandler)
	mux.HandleFunc("/chat", handlers.ChatHandler)
	mux.HandleFunc("/judge", handlers.JudgeHandler)
	mux.HandleFunc("/vote", handlers.VoteHandler)
	mux.HandleFunc("/ai", handlers.AiHandler)
	mux.HandleFunc("/aiwerewolves", handlers.AiWolvesteammateHandler)
	mux.HandleFunc("/aiwolveskill", handlers.AiwolveskillHandler)
	mux.HandleFunc("/aiseercheck", handlers.Aiseercheck)
	mux.HandleFunc("/aidevilcheck", handlers.Aidevilcheck)
	mux.HandleFunc("/aivote", handlers.Aivote)
	mux.HandleFunc("/aiselfetonationinformed", handlers.AiselfDetonationInformed)
	mux.HandleFunc("/voteout", handlers.Voteout)
	mux.HandleFunc("/aiwitchpoison", handlers.Aiwitchpoison)
	mux.HandleFunc("/aiantidote", handlers.Aiantidote)
	mux.HandleFunc("/nightinformation", handlers.Nightinformation)
	mux.HandleFunc("/endoflifeskill", handlers.EndOfLifeSkill)
	mux.HandleFunc("/endgame", handlers.Endgame)
	mux.HandleFunc("/aiguard", handlers.Aiguard)
	mux.HandleFunc("/aiknightskill", handlers.AiKnightSkill)
	mux.HandleFunc("/airoleinformed", handlers.Airoleinformed)
	mux.Handle("/", http.FileServer(http.Dir(serverFilePrefix+"")))
	mux.Handle("/voice", http.FileServer(http.Dir(serverFilePrefix+"voice")))
	mux.Handle("/cards", http.FileServer(http.Dir(serverFilePrefix+"cards")))
	return handler
}

func localPath() {
	if _, err := os.Stat("local"); err != nil {
		serverFilePrefix = "./dist/"
	}
}

func corsMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*") // 允许所有域名访问，也可以指定具体的域名
		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}
		next.ServeHTTP(w, r)
	})
}